package com.school.information.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.information.core.exception.ServiceException;
import com.school.information.dto.WechatAppUserDTO;
import com.school.information.entity.SysWechatUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.mapper.SysWechatUserMapper;
import com.school.information.service.SysWechatUserService;
import com.school.information.utils.AESUtil;
import com.school.information.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;

/**
 * (SysWechatUser)表服务实现类
 *
 * @author ycc
 * @since 2023-11-15 14:25:49
 */
@Service
@Slf4j
public class SysWechatUserServiceImpl extends ServiceImpl<SysWechatUserMapper, SysWechatUserEntity> implements SysWechatUserService {

    @Override
    public SysWechatUserEntity getByOpenid(String openid) {
        return this.getOne(Wrappers.<SysWechatUserEntity>lambdaQuery().eq(SysWechatUserEntity::getOpenid, openid));
    }

    @Override
    public String decryptWechatData(WechatAppUserDTO wechatAppUser) {
        // 从当前登录的用户中获取session_key
        String session_key = UserUtil.getWechatUserSessionKey();
        // 微信加密进行签名验证
        String validSignature = AESUtil.encode(wechatAppUser.getRawData() + session_key);
        if (!wechatAppUser.getSignature().equals(validSignature)) {
            log.error("##微信签名验证失败");
            throw new ServiceException(SysResultEnum.WECHAT_APP_VALID_SIGNATURE_FAIL);
        }
        String jsonStr = null;
        try {
            // 对加密数据进行解密
            byte[] resultByte = AESUtil.decrypt(Base64.decodeBase64(wechatAppUser.getEncryptedData()), Base64.decodeBase64(session_key),
                    Base64.decodeBase64(wechatAppUser.getIv()));
            jsonStr = new String(resultByte, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
            throw new ServiceException(e.getMessage());
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        return jsonStr;
    }
}
